/*****************************************************
                 fpc/file/ace4_save.c
5 dec 97 - don't dump ctgs with only cancelled
18 mar 98 - close file for dumping fingerprints
3sept98 - dump ePCR only if no STS of same name, after changing name
          back to st prefix from e prefix
******************************************************/
#include "fpp.h"
#include <fcntl.h>
#include <float.h>
#include <malloc.h>

extern int filCheck();
extern void getdatehead(), make_Zmap();
extern int Zbatch_flag;
extern char Zmap[50];
extern int Zmap_ace();
extern int Zg, Zimin, Zimax;
extern void map_extent();
extern void find_stretched_contigs();

static void ace_save_ctg();

FILE *fpace;
static char str[500];

static int ace_open(char *s)
{
char buf[1024];

   if (Zbatch_flag) return 1;
   if(strlen(dirName)>0) sprintf(buf, "%s/Ace", dirName);
   else sprintf(buf, "Ace");
   if(!filCheck(buf,"d")){
      if(strlen(dirName)==0) sprintf(buf,"mkdir ./Ace");
      else sprintf(buf,"mkdir %s%s",dirName,"/Ace");
      printf("adding Ace Directory\n");
      system(buf);
   }
   if(strlen(dirName)>0) 
      sprintf(buf, "%s/Ace/%s-%s.ace", dirName, fileName,s);
   else
      sprintf(buf, "Ace/%s-%s.ace", fileName,s);
   if((fpace = fopen(buf,"w")) == NULL ){
      displaymess("Cannot open file:");
      displaymess(buf);
      return 0; 
  }
  sprintf(str,"Save ace %s",buf);
  displaymess(str);
  printf("// Dump from FPC in ACE4 %s format\n", s);
  getdatehead(buf);
  fprintf(fpace, "// %s\n", buf); 
return 1;
}

/***********************************************************/
static void ace_all()
{
  int i;
  if (!ace_open("all")) return;
  for (i=1; i<=max_contig; i++) 
    if(contigs[i].count != 0 && !NoAce(i))
      ace_save_ctg(i);
  fclose(fpace);
}

/***********************************************************/
static void ace_seq()
{
int i;
    
   if (!ace_open("seq")) return;
   
   for (i=1; i<=max_contig; i++) {
     if (contigs[i].seq > 0 && !NoAce(i)) 
           ace_save_ctg(i);
   }
   fclose(fpace);
}

/***********************************************************/
static void ace_ctg(int num)
{
   sprintf(str,"ctg%d",num);
   if (!ace_open(str)) return;
   ace_save_ctg(num);
   fclose(fpace);
}

/***********************************************************/
static void ace_save_ctg(int num)
{  
  CLONE *clone;
  struct remark *pointer;
  struct markertop *mptr;
  struct markerctgpos *pos;
  struct marker *marker;
  char type[20], ptype[20];
  int  *index, found;
  int i, c;

  make_Zmap(num);
  if (arrayMax(markerdata) > 0) {
    index = (int *) malloc(arrayMax(markerdata) * sizeof(int));
    if (index==NULL) {
       displaymess("out of memory");
       return;
    } 
    for (i=0; i< arrayMax(markerdata); i++) index[i]=0;
  } else index=NULL;
 
  for (c= contigs[num].start; c != -1; c = clone->next) 
  {
    clone = arrp(acedata, c, CLONE); 
    fprintf(fpace,"\n%s : \"%s\"\n",clonetype[clone->class],clone->clone);
    strcpy(type,clonetype[clone->class]);
    
    fprintf(fpace,"Map %s Left %d.000\n", Zmap, clone->x);
    fprintf(fpace,"Map %s Right %d.000\n",Zmap, clone->y);
    if (Zimin > clone->x) Zimin = clone->x;
    if (Zimax < clone->y) Zimax = clone->y;
    
    if(clone->fp != NULL){
      fprintf(fpace,"Gel_number    %s\n",clone->fp->gelname);
      fprintf(fpace,"Bands  %d %d\n",clone->fp->b1,clone->fp->b2);
    }
    if(clone->mattype > PSPARENT){ /* i.e. if its a match */
      strcpy(ptype,clonetype[arrp(acedata, clone->parent, CLONE)->class]);
      if(clone->mattype & EXACT )
	fprintf (fpace,"Exact_match_to_%s \"%s\"\n", ptype, clone->match) ;
      else if(clone->mattype & APPROX)
	fprintf (fpace,"Approximate_match_to_%s \"%s\"\n", ptype, clone->match) ;	
      else if(clone->mattype & PSEUDO)
	fprintf (fpace,"Funny_match_to_%s \"%s\"\n", ptype, clone->match) ;	
    }    
    found=0;
    pointer=clone->remark;
    while(pointer!=NULL){
	fprintf(fpace,"Remark \"%s\"\n", pointer->message) ;
        if (strstr(pointer->message, "pace_ignore") != NULL) found = 1;
        pointer = pointer->next;
    }

    if (!found) 
        for (mptr = clone->marker; mptr!=NULL; mptr = mptr->nextmarker)
              index[mptr->markerindex] = 1;
    if (clone->seqstat) {
       fprintf(fpace,"\nSequence : %s\nMap %s With_%s %s\n",
              clone->clone, Zmap, clonetype[clone->class], clone->clone);
       fprintf(fpace,"Shotgun_type %s\n", seqtype[clone->seqtype]); /* ADD 19mar99 */
    }
  }
  for (i=0; i< arrayMax(markerdata); i++)
     if (index[i]) {
        marker =  arrp(markerdata, i, MARKER);
        for (pos = marker->pos; pos != NULL; pos = pos->next)
           if (pos->ctg == num) {
              char name[MARKER_SZ], type[25];
              int x;
                  /* if name exists with st instead of e prefix, don't print */
              if (marker->type==markPCR) {
                  char tmp[MARKER_SZ];
                  strcpy(tmp,&(marker->marker[1]));
                  sprintf(name,"s%s",tmp);
                  strcpy(type,"STS");
                  if(fppFind(markerdata,name,&x,markerOrder)) continue; 
              }
              else {
                  strcpy(name,marker->marker);
                  strcpy(type,markertype[marker->type]);
              }
              fprintf(fpace, "\n%s : %s\n", type, name);
              fprintf(fpace, "Map %s Position %d\n",Zmap, pos->pos);
              if(Zg) map_extent(i, num);
              break;
	    }
    }
  if (index!=NULL) free(index);
  i = Zmap_ace(fpace);
  find_stretched_contigs(i, num);
}

/***********************************************************/
static void save_clone_bands()
{
  int i=0;
  BOOL real = FALSE;
  int max; 
  CLONE *clone;
  char *clonename;

  max = arrayMax(acedata);
  while(!real && i<max){
    clonename = arrp(acedata,i,CLONE)->clone;
    if(clonename[0] != '!')
      real = TRUE;
    else
      i++;
  }
  if(!real){
    displaymess("No Data to export");
    return;
  }
  if (!ace_open("bands")) return;

  for(;i<arrayMax(acedata);i++){
    clone = arrp(acedata,i,CLONE);
    if(clone->fp != NULL && clone->class != CANCELLED){
      fprintf(fpace,"\n%s : \"%s\"\n",clonetype[clone->class],clone->clone);
      fprintf(fpace,"Bands  %d %d\n",clone->fp->b1,clone->fp->b2);
    }
  }
  fclose(fpace); /* 18 mar 98 */
}

/***********************************************************/
static int check2ctg(char *temp)
{
  int result;

  if(sscanf(temp,"%d",&result)){
    if(result<= max_contig){
      if(contigs[result].count!=0)
	return result;
      else
	displaymess("There are no clones in this contig");
    }
    else
      displaymess("Must be lower than the max contig");
  }
  else
    displaymess("Please input an integer");
  return 0;
}
static void request2ctg(char *temp)
{	       
  int ctg=0;

  ctg = check2ctg(temp);
  if(ctg) ace_ctg(ctg);
}

static void sub_ctg()
{
  int ctg=0;

  ctg = check2ctg(req2ctg);
  if(ctg) ace_ctg(ctg);
}
void save_as_ace()
{
  
  if(graphActivate(gsubmit)){ 
    graphClear();
    graphPop();
  }
  else{ 
    gsubmit = graphCreate (TEXT_FIT,"Save as Ace",.2,.2,.3,.20) ;
  }
  
  graphButton("Save All Contigs",ace_all,2.0,2.0);
  graphButton("Save Sequenced Contigs",ace_seq,2.0,4.0);
  graphButton("Save All Fingerprinted Clones",save_clone_bands,2.0,6.0);
  
  graphText("Contig:",2.0,9.0);
  graphTextEntry(req2ctg, 5, 9.0, 9.0,request2ctg);
  graphButton("Save",sub_ctg,15.0,9.0);

  graphButton("Close",graphDestroy,5.0,11.0);
  graphRedraw();
}
/***********************************************************
                 Zace_batch
************************************************************/
void Zace_batch(FILE *fp, char type) 
{
char buf[1024];
char s[3][20] = {"All contigs", "Seq contigs", "Clone Bands"};

  fpace = fp;
  fprintf(fpace,"// Batch Dump from FPC for Acedb in %s format\n", s[type-3]);
  getdatehead(buf);
  fprintf(fpace, "// %s\n", buf); 
  if (type==3) ace_all(); 
  else if (type==4) ace_seq(); 
  else if (type==5) save_clone_bands(); 
}
